﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebSoftSeo.Models;
using WebSoftSeo.Utility;

namespace WebSoftSeo.Controllers
{
    public class BlogController : Controller
    {
        WebSoftSeoEntities db = new WebSoftSeoEntities();
        //
        // GET: /Blog/

        public ActionResult Index(int page=0)
        {
            //var blogcategory = db.BlogCategories.ToList();
          int skip=0;
            if (page != 0)
            {
                skip =2 * (page-1);
            }
            int count = db.Blogs.Where(m => m.IsBanner == false || m.IsBanner == null).ToList().Count();
            ViewBag.count = count;
            var BlogIndex = db.Blogs.OrderByDescending(m => m.DateCreate).Where(m => m.IsBanner == false || m.IsBanner == null).Skip(skip).Take(2).ToList();
            return View(BlogIndex);
        }
        public ActionResult Detail(string title,int id = 0)
        {
           
            Blog blog = db.Blogs.Find(id);
            return View(blog);
        }

        public ActionResult _MonthFilter()
        {
           
            return PartialView();
        }
        public ActionResult MonthFilter(int year = 0, int month = 0, int page=0)
        {
            ViewBag.page = page;
            ViewBag.month = month;
            ViewBag.year = year;
            int skip = 0;
            if (page != 0)
            {
                skip = 2 * (page - 1);
            }
            var lstblog = db.Blogs.Where(m => m.DateCreate.Value.Month == month && m.DateCreate.Value.Year == year).ToList();
            ViewBag.count = lstblog.Count();
            var monthfilter = lstblog.OrderByDescending(m => m.DateCreate).Where(m => m.IsBanner == false || m.IsBanner == null).Skip(skip).Take(2).ToList();
            return View(monthfilter);
        }
        public ActionResult Category(string CategoryName, int id = 0, int page = 0)
        {
            ViewBag.id = id;
            int skip = 0;
            if (page != 0)
            {
                skip = 2 * (page - 1);
            }
            var lstblog = db.Blogs.OrderByDescending(m=>m.DateCreate).Where(m => m.CategoriesID == id).Skip(skip).Take(2).ToList();
            ViewBag.count = db.Blogs.Where(m => m.CategoriesID == id).Count();
            return View(lstblog);
        }
        public ActionResult _BlogCategory()
        {
            var blogcategory = db.BlogCategories.ToList();
            return PartialView(blogcategory);
        }
        public ActionResult _PopularBlogArticle()
        {
            var blogarticle = db.Blogs.OrderByDescending(m => m.DateCreate).Where(m=>m.IsBanner==null || m.IsBanner ==false).Take(6).ToList();
            return PartialView(blogarticle);
        }
        public ActionResult Create()
        {
            if (Session["UserName"] == null)
            {
                return RedirectToAction("Register", "User");
            }
            ViewBag.blogcategory = new SelectList(db.BlogCategories.ToList(), "ID", "Name");
            return View();
        }
        [HttpPost, ValidateInput(false)]
        public ActionResult Create(Blog blog)
        {
            ViewBag.blogcategory = new SelectList(db.BlogCategories.ToList(), "ID", "Name");
            if (ModelState.IsValid)
            {
                String NamePro = null;

                if (Request.Files["img1"] != null)
                {
                    HttpPostedFileBase file0 = Request.Files["img1"];
                    string fullname = Request.Files["img1"].FileName;
                    if (fullname != "")
                    {
                        NamePro = fullname.Substring(1 + fullname.LastIndexOf("\\"));
                        string rename = HelperSEO.ToSeoImage(blog.Title + DateTime.Now.Ticks + NamePro.Substring(NamePro.LastIndexOf(".")));
                        Resize(Server.MapPath("~/Images/Blog/"), rename, 737, 334, file0.InputStream);
                        //Resize(Server.MapPath("~/Images/OurClient/Img80.80/"), rename, , 80, file0.InputStream);
                        blog.ImagePath = rename;
                    }
                }
                blog.DateCreate = DateTime.Now;
                string user = Session["Email"].ToString();
                User usertest = db.Users.Where(m => m.Email == user).FirstOrDefault();
                blog.UserID = usertest.ID;
               

                db.Blogs.Add(blog);
                db.SaveChanges();
            }
            return Redirect("~/Blog/Index");
        }

        private ImageCodecInfo GetEncoderInfo(String mimeType)
        {
            int j;
            ImageCodecInfo[] encoders;
            encoders = ImageCodecInfo.GetImageEncoders();
            for (j = 0; j < encoders.Length; ++j)
            {
                if (encoders[j].MimeType == mimeType)
                    return encoders[j];
            }
            return null;
        }
        //
        // GET: /Admin/OurClient/Create
        public void Resize(string ImageSavePath, string fileName, int MaxWidthSideSize, int MaxHeightSidesize, Stream Buffer)
        {
            int intNewWidth;
            int intNewHeight;
            System.Drawing.Image imgInput = System.Drawing.Image.FromStream(Buffer);
            ImageCodecInfo myImageCodecInfo;
            myImageCodecInfo = GetEncoderInfo("image/jpeg");
            //
            System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality;
            EncoderParameters myEncoderParameters = new EncoderParameters(1);
            EncoderParameter myEncoderParameter;
            //Giá trị width và height nguyên thủy của ảnh;
            int intOldWidth = imgInput.Width;
            int intOldHeight = imgInput.Height;

            //Kiểm tra xem ảnh ngang hay dọc;
            int intMaxSideW;
            int intMaxSideH;
            /*if (intOldWidth >= intOldHeight)
            {
            intMaxSide = intOldWidth;
            }
            else
            {
            intMaxSide = intOldHeight;
            }*/
            //Để xác định xử lý ảnh theo width hay height thì bạn bỏ note phần trên;
            //Ở đây mình chỉ sử dụng theo width nên gán luôn intMaxSide= intOldWidth; ^^;
            intMaxSideW = intOldWidth;
            intMaxSideH = intOldHeight;
            if (intMaxSideW > MaxWidthSideSize | intMaxSideH > MaxHeightSidesize)
            {
                //Gán width và height mới.
                double dblCoefW = MaxWidthSideSize / (double)intMaxSideW;
                intNewWidth = Convert.ToInt32(dblCoefW * intOldWidth);
                double dblCoefH = MaxHeightSidesize / (double)intMaxSideH;
                intNewHeight = Convert.ToInt32(dblCoefH * intOldHeight);
            }
            else
            {
                //Nếu kích thước width/height (intMaxSide) cũ ảnh nhỏ hơn MaxWidthSideSize thì giữ nguyên //kích thước cũ;
                intNewWidth = intOldWidth;
                intNewHeight = intOldHeight;
            }


            //Tạo một ảnh bitmap mới;
            Bitmap bmpResized = new Bitmap(imgInput, intNewWidth, intNewHeight);
            //Phần EncoderParameter cho phép bạn chỉnh chất lượng hình ảnh ở đây mình để chất lượng tốt //nhất là 100L;
            myEncoderParameter = new EncoderParameter(myEncoder, 100L);
            myEncoderParameters.Param[0] = myEncoderParameter;
            //Lưu ảnh;
            bmpResized.Save(ImageSavePath + fileName, myImageCodecInfo, myEncoderParameters);

            //Giải phóng tài nguyên;
            //Buffer.Close();
            imgInput.Dispose();
            bmpResized.Dispose();
        }
    }
}
